import time
import os
import requests
import json
from urllib.request import urlopen
from json import load
from urllib import parse, request
from time import strftime, localtime


url = "http://192.168.31.15:8000/"
min = "%H:%M"
t = 1
# 下面是执行的命令
shells = "sudo bash /root/H1ve/restart.sh"
t1 = 1800
# 每30分钟检测一次
print('\033[32m正在测试执行中，请稍后')
os.system(shells)
DingDingToken = ""


def timesleepcheck():
    st = 0
    while st < 10:
        st += 1
        print('\033[34m正在加载中','\033[32m......','\033[34m',st)
        time.sleep(1)
    # 重启过后第一秒检测肯定是502，等待十秒重新检


def main_request(api_url, requests_data):
    req = request.Request(url=api_url, data=requests_data)
    req.add_header('Content-Type', 'application/json')
    r = request.urlopen(req)
    r_data = r.read().decode('utf-8')
    return r_data


def get_ip_a():
    my_ip = load(urlopen('https://api.ipify.org/?format=json'))['ip']
    # print('api.ipify.org', my_ip)
    print("Date >> 当前公网IP ", my_ip, "\n")
    return my_ip


def dingding(token,status_c):
    IP_A = get_ip_a()
    api_url = "https://oapi.dingtalk.com/robot/send?access_token=" + token
    requests_data = json.dumps({
        "msgtype": "markdown",
        "markdown": {
            "title": "H1ve状态监控",
            "text": "#### H1ve靶场平台状态监控 \n \n >当前状态" +str(status_c)+ "\n \n > 公网IP：" + IP_A + " \n \n > ###### M0x1n本地服务器 [机器人](https://pan.moxinwangluo.cn) \n"
        }
    }).encode('utf-8')
    main_request(api_url, requests_data)
   

# 初始执行
while t:
    timesleepcheck()
    q = requests.get(url)
    if q.status_code != 200:
        print('\033[32m|自检中|Time:',time.strftime(min, time.localtime()),'---------')
        print('\033[31m[错误] 当前状态非正常 ——',q.status_code)
        dingding(DingDingToken,q.status_code)
        os.system(shells)
        timesleepcheck()
        q = requests.get(url)
        if q.status_code != 200:
            print('\033[32m|自检中|Time:',time.strftime(min, time.localtime()),'---------')
            print('\033[31m[错误] 当前状态非正常 ——',q.status_code)
            dingding(DingDingToken,q.status_code)
        else:
            print('\033[32m|自检中|Time:',time.strftime(min, time.localtime()),'---------')
            print('\033[32m[正常] 当前已恢复正常 ——',q.status_code)
            dingding(DingDingToken,q.status_code)
        # fp = os.popen(shells, "r")
        # x = fp.read()
        # print(x)
    else:
        # 当前状态正常
        print('\033[32m|自检中|Time:',time.strftime(min, time.localtime()),'---------')
        print('\033[32m[正常] 当前状态正常 ——',q.status_code)
        dingding(DingDingToken,q.status_code)
    
     
    time.sleep(t1)



